<template>
  <div class="unsafe-driving-alarm bg-background text-foreground p-6">
    <h2 class="mb-6 text-2xl font-bold">电子运单管理</h2>

    <div class="bg-card text-card-foreground mb-4 rounded p-4 shadow">
      <!-- Search Form -->
      <QueryForm :model="filters" :formItems="formItems" @search="loadData" @reset="resetFilters" />
    </div>


    <!-- Action Buttons -->
    <div class="mb-4 space-x-2">
      <el-button style="width: 75px; height: 30px;" @click="deleteSelected">
        删除
      </el-button>
      <el-button @click="exportData(incidentData, '电子运单管理')" style="width: 75px; height: 30px;">导出</el-button>
    </div>
    <!-- Data Table -->
    <div class="bg-card text-card-foreground my-6 rounded shadow-md">

      <el-table v-loading="loading" :data="paginatedData" style="width: 100%" ref="table" align="center"
        class="data-table" :header-cell-style="headerCellStyle" :row-key="rowKey"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="序号" width="55" header-align="center" align="center">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="WAYBILL_NUMBER" label="运单编号" header-align="center" align="center"></el-table-column>
        <el-table-column prop="CONSIGNEE_NAME" label="收货人名称" header-align="center" align="center"></el-table-column>
        <el-table-column prop="CONTACT_NUMBER" label="联系电话" header-align="center" align="center"></el-table-column>
        <el-table-column prop="DESTINATION" label="目的地" header-align="center" align="center"></el-table-column>
        <el-table-column prop="DRIVER_NAME" label="驾驶员姓名" header-align="center" align="center"></el-table-column>
        <el-table-column prop="DRIVER_NUMBER" label="联系电话" header-align="center" align="center"></el-table-column>
        <el-table-column prop="LICENSE_NUMBER" label="车牌号码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="ROAD_NUMBER" label="道路运输证号" header-align="center" align="center"></el-table-column>
        <el-table-column prop="HAZARDOUS_NAME" label="危险物品运输名称" header-align="center" align="center"></el-table-column>
        <el-table-column prop="QUANTITY" label="数量" header-align="center" align="center"></el-table-column>
        <el-table-column prop="UNIT" label="单位" header-align="center" align="center"></el-table-column>
        <el-table-column label="操作" header-align="center" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="addNew(scope.row)" link>详情</el-button>
          </template>
        </el-table-column>

      </el-table>
    </div>
    <!-- Pagination -->
    <div class="border-border flex items-center justify-between border-t px-4 py-3 sm:px-6">
      <div>
        <p class="text-sm text-muted-foreground">
          一共检索到 <span class="font-medium total-num">{{ totalItems }}</span> 条信息
        </p>
      </div>
      <div class="flex items-center space-x-2">
        <button @click="prevPage" :disabled="currentPage === 1" class="btn btn-secondary btn-sm"
          :class="{ 'opacity-50 cursor-not-allowed': currentPage === 1 }">
          上一页
        </button>
        <span class="text-sm text-muted-foreground">
          {{ currentPage }} / {{ totalPages }}
        </span>
        <button @click="nextPage" :disabled="currentPage === totalPages" class="btn btn-secondary btn-sm"
          :class="{ 'opacity-50 cursor-not-allowed': currentPage === totalPages }">
          下一页
        </button>
      </div>
    </div>


    <!-- 替换 el-dialog 为原生对话框 -->
    <el-dialog class="dialog-from dialog-set" v-model="dialogVisible" title="
电子运单详情" width="550" destroy-on-close align-center>
      <div class="tablename">
        <div
          style="width: 10px; height: 10px; background-color:rgba(2, 125, 180, 1);margin-right: 10px;border:1px solid;">
        </div>
        <span>基本信息</span>
      </div>
      <div>
        <el-image style="width: 450px;" :src="imgdata"></el-image>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="dialogVisible = false">确认</el-button>
          <el-button @click="dialogVisible = false">
            取消
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance()
import * as XLSX from 'xlsx'
import { exportData } from '#/utils/exportfile.js'
// import {
//   PlusIcon,
//   TrashIcon,
//   UploadIcon,
//   DownloadIcon,
//   SettingsIcon,
//   ChevronLeftIcon,
//   ChevronRightIcon,
// } from 'lucide-vue-next'

// 1. 声明所有响应式变量
const filters = ref({
  WAYBILL_NUMBER: '',

})
const table = ref()
const apiBaseUrl = ref(proxy.$currentUrl + '/api/electronic_waybill')

const rowKey = (row) => row.ID // 设置行的唯一标识
const incidentData = ref([])
const currentPage = ref(1)
const itemsPerPage = 10
const selectAll = ref(false)
const dialogVisible = ref(false)
const isEditing = ref(false)
const formData = ref({
  incidentCode: '',
  incidentType: '',
  description: '',
  location: '',
  date: '',
  monitoringDevice: '',
  licensePlate: '',
  driver: '',
  contactNumber: '',
  notes: '',
})
const selectedIds = ref([])
const pageSize = ref(10)
// 2. 添加计算属性
const totalItems = computed(() => incidentData.value.length)
const totalPages = computed(() => Math.ceil(totalItems.value / pageSize.value))
const imgdata = ref('')
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return incidentData.value.slice(start, end)
})
const handleSelectionChange = (selected) => {
  selectedIds.value = selected
}
const displayedPages = computed(() => {
  const range = 2
  const pages = []
  for (
    let i = Math.max(1, currentPage.value - range);
    i <= Math.min(totalPages.value, currentPage.value + range);
    i++
  ) {
    pages.push(i)
  }
  return pages
})

// 3. 添加方法
const loadData = async () => {
  // 模拟API调用加载数据


  try {
    loading.value = true
    const response = await axios.get(`${apiBaseUrl.value}/search`, {
      params: filters.value,
    })



    incidentData.value = response.data.map(equipment => ({ ...equipment, selected: false }))


    loading.value = false
  } catch (error) {
    console.error('搜索不安全驾驶行为失败:', error)
    alert(
      '搜索不安全驾驶行为失败: ' + (error.response?.data?.message || error.message),
    )
  }
}

const resetFilters = () => {
  filters.value = {
    WAYBILL_NUMBER: '',

  }
  loadData()
  currentPage.value = 1
}

const addNew = async (row) => {

  const response = await axios.get(`${apiBaseUrl.value}/${row.ELECTRONIC}`,)

  imgdata.value = response.data.url



  dialogVisible.value = true
}

const deleteSelected = async () => {

  if (selectedIds.value.length === 0) {
    alert('请选择要删除的记录')
    return
  }
  if (confirm(`确定要删除选中的 ${selectedIds.value.length} 条记录吗？`)) {
    try {
      await Promise.all(selectedIds.value.map(async item => {
        await axios.delete(`${apiBaseUrl.value}/${item.ID}`)
      }
      ))
      await alert('删除成功')
      selectedIds.value = []
      table.value.clearSelection()
      await loadData()
    } catch (error) {
      console.error('删除记录失败:', error)
      alert('删除记录失败: ' + (error.response?.data?.message || error.message))
    }
  }
}

const toggleSelectAll = () => {
  selectAll.value = !selectAll.value
  incidentData.value.forEach((item) => (item.selected = selectAll.value))
}
// 辅助函数
const getVehicleTypeText = (type) => {
  const types = {
    1: '一般事件',
    2: '紧急事件',
    3: '重大事件',
  }
  return types[type] || ''
}
// 添加格式化日期时间的辅助函数
const formatDateTimeForInput = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toISOString().slice(0, 16) // 格式为 "YYYY-MM-DDTHH:mm"
}

const formItems = ref([
  {
    label: '运单编号：',
    model: 'WAYBILL_NUMBER',
    type: 'input',
    placeholder: '请输入',
  },

]);
// 表头样式
const headerCellStyle = {
  height: '30px', // 设置表头高度
  lineHeight: '30px', // 设置行高以垂直居中
  backgroundColor: '#f2f2f2', // 可选：设置背景颜色
  // fontSize: '16px', // 可选：设置字体大小
};
const isDialogType = ref('')
const loading = ref(false)
// 添加格式化日期时间的函数
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toLocaleString()
}
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
    loadData()
  }
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    loadData()
  }
}
const showSettings = ref(false);
const openSettings = () => {
  showSettings.value = true
}
// 4. 初始化数据
onMounted(() => {
  loadData()
})

// 3. 修改对话框关闭函数
const closeDialog = () => {
  dialogVisible.value = false
  formData.value = {
    incidentCode: '',
    incidentType: '',
    description: '',
    location: '',
    date: '',
    monitoringDevice: '',
    licensePlate: '',
    driver: '',
    contactNumber: '',
    notes: '',
  }
}
const radio1 = ref('启用')
const radio2 = ref('启用')
const radio3 = ref('启用')
const radio4 = ref('启用')
const setFrom = ref({
  SPEEDING: 0,
  PARKING: '科技东路',
  FOLLOW_BEGIN: '科技东路',
  FOLLOW_END: '科技东路',
  TIME_BEGIN: '',
  TIME_END: '',
})
const setSubmit = () => {
  alert('设置成功');
  showSettings.value = false;
}
</script>

<style scoped>
.btn {
  @apply rounded-md px-4 py-2 font-medium transition duration-150 ease-in-out focus:outline-none focus:ring-2 focus:ring-offset-2;
}

.btn-primary {
  @apply bg-primary text-primary-foreground hover:bg-primary/90;
}

.btn-secondary {
  @apply bg-secondary text-secondary-foreground hover:bg-secondary/80;
}

.btn-destructive {
  @apply bg-destructive text-destructive-foreground hover:bg-destructive/90;
}
</style>
<style lass="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
  /* 按钮居中对齐 */
}

.total-num {
  color: #02a7f0;
  font-size: 28px;
}

:deep(.dialog-from.el-dialog) {
  padding-top: 0;
  padding-left: 0;
  padding-right: 0;
}

:deep(.dialog-from .el-dialog__header) {
  padding: 11px 17px;
  background-color: #f2f2f2;
  font-size: 18px;
}

.dialog-from :deep(.el-dialog__body) {
  padding-left: 48px;
  padding-right: 48px;
  padding-top: 20px;
}

.body-item {}



.box-title {
  margin-bottom: 10px;
}

.box-color {
  display: inline-block;
  width: 10px;
  height: 10px;
  background-color: #027db4;
  margin-right: 10px;
}



.box-content {
  /* height: 80px; */
}

.row-item {
  height: 80px;
  /* margin-bottom: 20px; */
}

.input-time {
  display: inline-block;
  border-radius: 0;
  margin-top: 0;
  box-shadow: 0 0 0 1px #dcdfe6;
  width: 120px;
  height: 25px;
}

.input-time:hover {
  box-shadow: 0 0 0 1px #c0c4cc;
}

.upload-demo {
  position: relative;
  display: inline-block;
  width: 100%;
}

.upload-demo :deep(.el-upload) {
  width: 100%;
}

.input-upload {
  width: 100%;
}

:deep(.dialog-set .el-dialog__body) {
  padding: 0 27px;
}

.body-set-item {
  margin-top: 20px;
  padding: 0 31px;
}

.box-set-color {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #02A7F0;
  margin-right: 10px;
}

.box-content-item {
  padding-left: 20px;
  font-size: 12px;
}

:deep(.set-input .el-input__wrapper) {
  padding: 0;
  border-radius: 0;
}

:deep(.set-input .el-input__wrapper .el-input__inner) {
  text-align: center;
}

.set-select {
  width: 90px;
}

:deep(.set-select .el-select__wrapper) {
  font-size: 12px;
  padding: 0 5px 0 0;
  text-align: center;
  border-radius: 0;
}
</style>
